package invest;

import invest.strategy.SetCookieJob;
import invest.strategy.impl.AbstractStrategy;
import invest.utils.QuartzManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Map;

@Component
@PropertySource({"config.properties"})
public class Start implements CommandLineRunner {
	private final String COOKIE_JOB_NAME = "cookie_job";
	private final String COOKIE_TRIGGER_NAME = "cookie_trigger";
	private final String COOKIE_JOB_GROUP_NAME = "cookie_group";
	private final String COOKIE_TRIGGER_GROUP_NAME = "cookie_trigger_group";
	@Value("${COOKIECRON}")
	private String cookieCron;
	private static final Logger log = LoggerFactory.getLogger(Start.class);

	@Autowired
	@Qualifier("GetStrategy")
	Map<String, AbstractStrategy> maps;
	@Override
	public void run(String... args) throws Exception {

		try {
			log.info("任务开始");
			executeStrategy();
			QuartzManager.addJob(COOKIE_JOB_NAME, COOKIE_TRIGGER_NAME, COOKIE_JOB_GROUP_NAME, COOKIE_TRIGGER_GROUP_NAME, SetCookieJob.class, cookieCron);

		} catch (Exception e) {
			throw e;
		}
	}
	private void executeStrategy() throws IllegalAccessException, InstantiationException {
		if (!CollectionUtils.isEmpty(maps)) {
			for (String key :
					maps.keySet()) {
				final AbstractStrategy strategy=maps.get(key);
				Class clazz=strategy.getClass();

				String jobName = clazz.getName() + "_jobName";
				String triggerName = clazz.getName() + "_triggerName";
				String groupName = clazz.getName() + "_groupName";
				String triggerGroupName = clazz.getName() + "_triggerGroupName";
				Field[] fields=clazz.getSuperclass().getDeclaredFields();
				String cron = "";
				for (int i = 0; i < fields.length; i++) {
					if (fields[i].getName().equals("cron")) {
						Object object = clazz.newInstance();
						cron= (String) fields[i].get(object);
					}
				}
				QuartzManager.addJob(jobName, triggerName, groupName, triggerGroupName, clazz, cron);
			}
		}
	}

}
